use egui::{Color32, RichText};
use display_info;

fn wavelength_to_p3(wavelength: f32) -> [f32; 3] {
    let x = (wavelength - 380.0) / 400.0;
    
    // CIE 1931色匹配函数近似计算
    let r = 1.056 * (1.0 / (x + 0.129)).exp() * (1.0 - (x - 0.745).powi(2)/0.015)
        .clamp(0.0, 1.0);
    let g = 1.2 * (1.0 / (x + 0.108)).exp() * (1.0 - (x - 0.550).powi(2)/0.030)
        .clamp(0.0, 1.0);
    let b = 0.8 * (1.0 / (x + 0.091)).exp() * (1.0 - (x - 0.435).powi(2)/0.020)
        .clamp(0.0, 1.0);
    
    // 应用gamma校正
    let gamma = 2.1;
    [r.powf(1.0/gamma), g.powf(1.0/gamma), b.powf(1.0/gamma)]
}

#[derive(Default)]
struct ColorApp {
    wavelength: f32,
    width: f32,
    height: f32,
    left_copy_time: Option<std::time::Instant>,
    right_copy_time: Option<std::time::Instant>,
}

impl eframe::App for ColorApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        let linear_rgb = wavelength_to_p3(self.wavelength);
        let gamma = 2.4;
        let corrected_rgb = [
            linear_rgb[0].powf(1.0/gamma),
            linear_rgb[1].powf(1.0/gamma),
            linear_rgb[2].powf(1.0/gamma)
        ];
    
        let linear_color = Color32::from_rgb(
            (linear_rgb[0] * 255.0) as u8,
            (linear_rgb[1] * 255.0) as u8,
            (linear_rgb[2] * 255.0) as u8
        );
        let corrected_color = Color32::from_rgb(
            (corrected_rgb[0] * 255.0) as u8,
            (corrected_rgb[1] * 255.0) as u8,
            (corrected_rgb[2] * 255.0) as u8
        );
    
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.vertical(|main_ui| {
                main_ui.vertical_centered(|ui| {
                    ui.heading(format!(
                        "波长：{:.0}nm",
                        self.wavelength
                    ));
                });
                main_ui.add_space(20.0);
                main_ui.horizontal(|ui| {
                    ui.label("380nm");
                    ui.add(egui::Slider::new(&mut self.wavelength, 380.0..=780.0).text("波长选择"));
                    ui.label("780nm");
                });
    
                main_ui.columns(2, |columns| {
                    columns[0].vertical(|ui| {
                        ui.set_width(self.width * 0.5);
                        ui.set_height(self.height * 1.0);
                        egui::Frame::NONE
                            .fill(linear_color)
                            .show(ui, |ui| {
                                ui.vertical_centered(|ui| {
                                    let text_color = if (linear_color.r() as f32 * 0.299 + linear_color.g() as f32 * 0.587 + linear_color.b() as f32 * 0.114) / 255.0 > 0.5 { Color32::BLACK } else { Color32::WHITE };
                                    ui.heading(RichText::new("原始色值").color(text_color));
                                    let color_text = format!(
                                        "#{:02X}{:02X}{:02X}",
                                        linear_color.r(), linear_color.g(), linear_color.b()
                                    );
                                    if ui.add(egui::Label::new(RichText::new(&color_text).strong().color(text_color)).sense(egui::Sense::click())).double_clicked() {
                                        ctx.copy_text(color_text.clone());
                                        self.left_copy_time = Some(std::time::Instant::now());
                                    }

                                    if let Some(time) = self.left_copy_time {
                                        if time.elapsed().as_secs_f32() < 0.75 {
                                            ui.label("✓ 已复制");
                                        }
                                    }
                                });
                            });
                    });
    
                    columns[1].vertical(|ui| {
                        ui.set_width(self.width * 0.5);
                        ui.set_height(self.height * 1.0);
                        egui::Frame::NONE
                            .fill(corrected_color)
                            .show(ui, |ui| {
                                ui.vertical_centered(|ui| {
                                    let text_color = if (corrected_color.r() as f32 * 0.299 + corrected_color.g() as f32 * 0.587 + corrected_color.b() as f32 * 0.114) / 255.0 > 0.5 { Color32::BLACK } else { Color32::WHITE };
                                    ui.heading(RichText::new("Gamma校正后").color(text_color));
                                    let color_text = format!(
                                        "#{:02X}{:02X}{:02X}",
                                        corrected_color.r(), corrected_color.g(), corrected_color.b()
                                    );
                                    if ui.add(egui::Label::new(RichText::new(&color_text).strong().color(text_color)).sense(egui::Sense::click())).double_clicked() {
                                        ctx.copy_text(color_text.clone());
                                        self.right_copy_time = Some(std::time::Instant::now());
                                    }

                                    if let Some(time) = self.right_copy_time {
                                        if time.elapsed().as_secs_f32() < 0.75 {
                                            ui.label("✓ 已复制");
                                        }
                                    }
                                });
                            });
                    });
                });
            });
        });
    }
}

fn main() -> eframe::Result<()> {
    let display_info = display_info::DisplayInfo::all()
        .unwrap_or_default()
        .into_iter()
        .next()
        .unwrap_or_else(|| display_info::DisplayInfo {
            id: 0,
            name: "Default".into(),
            width: 800,
            height: 600,
            x: 0,
            y: 0,
            scale_factor: 1.0,
            rotation: 0.0,
            frequency: 60.0,
            friendly_name: "Default".into(),
            height_mm: 344,
            width_mm: 611,
            is_primary: true,
            raw_handle: 0,
        });

    let window_width = (display_info.width as f32 / 4.0).round();
    let window_height = (display_info.height as f32 / 5.0).round();

    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([window_width, window_height])
            .with_position(egui::pos2(display_info.x as f32, display_info.y as f32))
            .with_resizable(false),
        ..eframe::NativeOptions::default()
    };

    eframe::run_native(
        "波长颜色展示",
        options,
        Box::new(|cc| {
            // 设置支持中文的字体
            let mut fonts = egui::FontDefinitions::default();
            fonts.font_data.insert(
                "MiSans Light".to_owned(),
                egui::FontData::from_static(include_bytes!("../MiSans-Light.ttf")).into()
            );
            fonts
                .families
                .get_mut(&egui::FontFamily::Proportional)
                .unwrap()
                .insert(0, "MiSans Light".to_string());
            cc.egui_ctx.set_fonts(fonts);

            Ok(Box::new(ColorApp {
                wavelength: 550.0,
                width: window_width,
                height: window_height,
                left_copy_time: None,
                right_copy_time: None,
            }))
        })
    )
}
